package com.jy.modules.cims.creditright.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.data.common.dao.TCMmCooperorgDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditPackageDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;
import com.jy.modules.cims.data.dao.OrgAccountDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditDetailQueryDto;

/**
 * @description 机构台账服务层。
 * @author shengzhoutao
 * @date 2015-01-07 16:21:57
 */
@Service("com.jy.modules.cims.creditright.service.OrgAccountService")
public class OrgAccountService {
	private static final Logger logger = LoggerFactory.getLogger(OrgAccountService.class);

	@Autowired
	private OrgAccountDao orgAccountDao;

	@Autowired
	public TCMmCreditPackageDao creditPackageDao;

	@Autowired
	public TCMmCooperorgDao cooperorgDao;

	/**
	 * @description 机构台账查询列表。 <br>
	 *              如果不传入合作机构编号，将查询所有合作机构台账。
	 * @author shengzhoutao
	 * @param creditDetailQueryDto
	 *            查询条件对象
	 * @return List<CreditDetailDto> <br>
	 *         CreditDetailDto实体对象的字段取值如下<br>
	 *         cooperorgCode：合作机构编号<br>
	 *         cooperorgName： 合作机构名称<br>
	 *         packageRows： 债权包数量<br>
	 *         creditRows： 债权明细数量 <br>
	 *         thisCreditorValue：当前债权价值合计<br>
	 *         dealMakeCreditorValue： 转让债权价值合计<br>
	 *         wayMakeCreditorValue： 在途债权价值合计
	 */
	public List<CreditDetailDto> getCreditValueForOrgByPaging(Map<String, Object> searchParams) {
		if (null == searchParams) {
			return null;
		}
		CreditDetailQueryDto dto = (CreditDetailQueryDto) searchParams.get("dto");
		logger.info("合作机构编号:::" + dto.getCooperorgCode());

		// 分页查询合作机构信息
		TCMmCooperorgDTO cooperorgDTO = new TCMmCooperorgDTO();
		cooperorgDTO.setCooperorgCode(dto.getCooperorgCode());
		searchParams.put("dto", cooperorgDTO);
		List<TCMmCooperorgDTO> cooperorgList = cooperorgDao.searchTCMmCooperorgByPaging(searchParams);

		List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
		if (CollectionsUtils.isEmpty(cooperorgList)) {
			return result;
		}

		CreditDetailQueryDto creditDetailQueryDto = null;

		// 批量统计债权价值
		List<CreditDetailQueryDto> creditDetailQueryDtoList = new ArrayList<CreditDetailQueryDto>();
		for (TCMmCooperorgDTO cooperorg : cooperorgList) {
			creditDetailQueryDto = new CreditDetailQueryDto();
			creditDetailQueryDto.setCooperorgCode(cooperorg.getCooperorgCode());

			creditDetailQueryDtoList.add(creditDetailQueryDto);
		}
		List<CreditDetailDto> creditValueList = orgAccountDao.batchStatCreditValueForOrg(creditDetailQueryDtoList);

		// 批量统计债权包个数
		List<CreditDetailDto> cooperorgCountList = orgAccountDao.batchStatCreditPackageCount(creditDetailQueryDtoList);

		// 批量统计在途债权价值
		creditDetailQueryDtoList.clear();
		for (TCMmCooperorgDTO cooperorg : cooperorgList) {
			creditDetailQueryDto = new CreditDetailQueryDto();
			creditDetailQueryDto.setCooperorgCode(cooperorg.getCooperorgCode());
			creditDetailQueryDto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WAY);// 债权状态:01-在途

			creditDetailQueryDtoList.add(creditDetailQueryDto);
		}

		List<CreditDetailDto> mayList = orgAccountDao.batchStatCreditValueForOrg(creditDetailQueryDtoList);

		// 组装数据返回对象集合
		CreditDetailDto creditDetailDto = null;
		OrgAccountServiceUtils utils = new OrgAccountServiceUtils();
		for (TCMmCooperorgDTO cooperorg : cooperorgList) {
			String cooperorgCode = cooperorg.getCooperorgCode();
			String cooperorgName = cooperorg.getCooperorgName();

			creditDetailDto = utils.getCreditDetailDto(cooperorgCode, cooperorgCountList);
			int packageRows = creditDetailDto.getCountRecord();

			creditDetailDto = utils.getCreditDetailDto(cooperorgCode, creditValueList);
			int creditRows = creditDetailDto.getCountRecord();
			BigDecimal thisCreditorValue = creditDetailDto.getThisCreditorValue();
			BigDecimal dealMakeCreditorValue = creditDetailDto.getThisMakeCreditorValue();

			creditDetailDto = utils.getCreditDetailDto(cooperorgCode, mayList);
			BigDecimal wayMakeCreditorValue = creditDetailDto.getThisMakeCreditorValue();

			creditDetailDto = new CreditDetailDto();
			creditDetailDto.setCooperorgCode(cooperorgCode);// 合作机构编号
			creditDetailDto.setCooperorgName(cooperorgName);// 合作机构名称
			creditDetailDto.setPackageRows(packageRows);// 债权包数量
			creditDetailDto.setCreditRows(creditRows);// 债权明细数量
			creditDetailDto.setThisCreditorValue(thisCreditorValue);// 当前债权价值合计
			creditDetailDto.setDealMakeCreditorValue(dealMakeCreditorValue);// 转让债权价值合计
			creditDetailDto.setWayMakeCreditorValue(wayMakeCreditorValue);// 在途债权价值合计
			result.add(creditDetailDto);
		}

		creditDetailDto = null;
		creditDetailQueryDto = null;
		creditDetailQueryDtoList = null;
		utils = null;

		return result;
	}

	/**
	 * @description 债权包台账查询列表。 <br>
	 *              合作机构编号为必输入参数。 <br>
	 * @author shengzhoutao
	 * @param creditDetailQueryDto
	 *            查询条件对象
	 * @return List<CreditDetailDto> <br>
	 *         CreditDetailDto实体对象的字段取值如下<br>
	 *         cooperorgCode：合作机构编号<br>
	 *         cooperorgName： 合作机构名称<br>
	 *         packageNum: 债权包名称<br>
	 *         contractCode:合约编号<br>
	 *         creditRows： 债权明细数量 <br>
	 *         thisCreditorValue：当前债权价值合计<br>
	 *         dealMakeCreditorValue： 转让债权价值合计<br>
	 *         wayMakeCreditorValue： 在途债权价值合计<br>
	 * @throws Exception
	 */
	public List<CreditDetailDto> getCreditValueForPackageByPaging(Map<String, Object> searchParams) throws Exception {
		if (null == searchParams) {
			return null;
		}

		CreditDetailQueryDto dto = (CreditDetailQueryDto) searchParams.get("dto");
		String cooperorgCode = dto.getCooperorgCode();
		String packageNum = dto.getPackageNum();
		String contractCode = dto.getContractCode();
		logger.info("合作机构编号:::" + cooperorgCode);
		logger.info("债权包名称:::" + packageNum);
		logger.info("合约编号:::" + contractCode);

		if (!SimpleStringUtils.hasText(cooperorgCode)) {
			throw new Exception("合作机构编号为空！");
		}

		TCMmCooperorgDTO cooperorgDTO = new TCMmCooperorgDTO();
		cooperorgDTO.setCooperorgCode(cooperorgCode);
		searchParams.put("dto", cooperorgDTO);
		List<TCMmCooperorgDTO> cooperorgList = cooperorgDao.searchTCMmCooperorg(searchParams);
		if (CollectionsUtils.isEmpty(cooperorgList)) {
			return null;
		}
		String cooperorgName = cooperorgList.get(0).getCooperorgName();

		// 分页查询债权包信息
		TCMmCreditPackageDTO creditPackageDTO = new TCMmCreditPackageDTO();
		creditPackageDTO.setCooperorgCode(cooperorgCode);
		creditPackageDTO.setCreditPackageName(packageNum);
		creditPackageDTO.setContractCode(contractCode);
		searchParams.put("dto", creditPackageDTO);
		List<TCMmCreditPackageDTO> creditPackageList = creditPackageDao.searchTCMmCreditPackageByPaging(searchParams);

		List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
		if (CollectionsUtils.isEmpty(creditPackageList)) {
			return result;
		}

		CreditDetailQueryDto creditDetailQueryDto = null;

		// 批量统计债权价值
		List<CreditDetailQueryDto> creditDetailQueryDtoList = new ArrayList<CreditDetailQueryDto>();
		for (TCMmCreditPackageDTO creditPackage : creditPackageList) {
			creditDetailQueryDto = new CreditDetailQueryDto();
			creditDetailQueryDto.setCooperorgCode(cooperorgCode);
			creditDetailQueryDto.setPackageNum(creditPackage.getCreditPackageName());
			creditDetailQueryDto.setContractCode(creditPackage.getContractCode());

			creditDetailQueryDtoList.add(creditDetailQueryDto);
		}
		List<CreditDetailDto> creditValueList = orgAccountDao.batchStatCreditValueForPackage(creditDetailQueryDtoList);

		// 批量统计在途债权价值
		creditDetailQueryDtoList.clear();
		for (TCMmCreditPackageDTO creditPackage : creditPackageList) {
			creditDetailQueryDto = new CreditDetailQueryDto();
			creditDetailQueryDto.setCooperorgCode(cooperorgCode);
			creditDetailQueryDto.setPackageNum(creditPackage.getCreditPackageName());
			creditDetailQueryDto.setContractCode(creditPackage.getContractCode());
			creditDetailQueryDto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WAY);// 债权状态:01-在途

			creditDetailQueryDtoList.add(creditDetailQueryDto);
		}

		List<CreditDetailDto> mayList = orgAccountDao.batchStatCreditValueForPackage(creditDetailQueryDtoList);

		// 组装数据返回对象集合
		CreditDetailDto creditDetailDto = null;
		OrgAccountServiceUtils utils = new OrgAccountServiceUtils();
		for (TCMmCreditPackageDTO creditPackage : creditPackageList) {
			packageNum = creditPackage.getCreditPackageName();
			contractCode = creditPackage.getContractCode();

			creditDetailDto = utils.getCreditDetailDto(cooperorgCode, packageNum, creditValueList);
			int creditRows = creditDetailDto.getCountRecord();
			BigDecimal thisCreditorValue = creditDetailDto.getThisCreditorValue();
			BigDecimal dealMakeCreditorValue = creditDetailDto.getThisMakeCreditorValue();

			creditDetailDto = utils.getCreditDetailDto(cooperorgCode, packageNum, mayList);
			BigDecimal wayMakeCreditorValue = creditDetailDto.getThisMakeCreditorValue();

			creditDetailDto = new CreditDetailDto();
			creditDetailDto.setCooperorgCode(cooperorgCode);// 合作机构编号，传参数用机构编号
			creditDetailDto.setCooperorgName(cooperorgName);// 合作机构名称，页面显示用机构名称
			creditDetailDto.setPackageNum(packageNum);// 债权包名称
			creditDetailDto.setContractCode(contractCode);// 合约编号
			creditDetailDto.setPackageStr(packageNum + "(合约编号:" + contractCode + ")");// 同一机构可能存在相同的债权包，加上合约编号可以区分唯一。
			creditDetailDto.setCreditRows(creditRows);// 债权明细数量
			creditDetailDto.setThisCreditorValue(thisCreditorValue);// 当前债权价值合计
			creditDetailDto.setDealMakeCreditorValue(dealMakeCreditorValue);// 转让债权价值合计
			creditDetailDto.setWayMakeCreditorValue(wayMakeCreditorValue);// 在途债权价值合计
			result.add(creditDetailDto);
		}

		creditDetailDto = null;
		creditDetailQueryDto = null;
		creditDetailQueryDtoList = null;
		utils = null;

		return result;
	}

	/**
	 * @description 机构台账，分页查询符合条件的债权明细。 <br>
	 *              查询某一合作机构的债权明细，合作机构编号为必须传入值。其它查询辅助参数：债权包名称、债权转让编号、债权编号。 <br>
	 * @author shengzhoutao
	 * @param searchParams
	 *            参数，dto的存放对象为CreditDetailQueryDto
	 * @return List<CreditDetailDto>
	 * @throws Exception
	 */
	public List<CreditDetailDto> searchCreditDetailByPaging(Map<String, Object> searchParams) throws Exception {
		if (null == searchParams || null == searchParams.get("dto")) {
			return null;
		}

		CreditDetailQueryDto dto = (CreditDetailQueryDto) searchParams.get("dto");
		String cooperorgCode = dto.getCooperorgCode();
		String packageNum = dto.getPackageNum();
		String transferId = dto.getTransferId();
		String creditCode = dto.getCreditCode();
		String creditorStatus = dto.getCreditorStatus();

		logger.info("合作机构编号:::" + cooperorgCode);
		logger.info("债权包名称:::" + packageNum);
		logger.info("债权转让编号:::" + transferId);
		logger.info("债权编号:::" + creditCode);
		logger.info("债权状态:::" + creditorStatus);

		if (!SimpleStringUtils.hasText(cooperorgCode)) {
			throw new Exception("合作机构编号为空！");
		}

		searchParams.put("dto", dto);

		return orgAccountDao.searchCreditDetailByPaging(searchParams);
	}

	/**
	 * 
	 * @author shengzhoutao
	 * 
	 */
	class OrgAccountServiceUtils {
		/**
		 * @description
		 * @author shengzhoutao
		 * @param cooperorgCode
		 * @param list
		 * @return
		 */
		private CreditDetailDto getCreditDetailDto(final String cooperorgCode, final Collection<CreditDetailDto> list) {
			if (!SimpleStringUtils.hasText(cooperorgCode) || CollectionsUtils.isEmpty(list)) {
				return new CreditDetailDto();
			}
			for (CreditDetailDto credit : list) {
				if (cooperorgCode.equals(credit.getCooperorgCode())) {
					return credit;
				}
			}
			return new CreditDetailDto();
		}

		/**
		 * @description
		 * @author shengzhoutao
		 * @param cooperorgCode
		 * @param packageNum
		 * @param list
		 * @return
		 */
		private CreditDetailDto getCreditDetailDto(final String cooperorgCode, String packageNum, final Collection<CreditDetailDto> list) {
			if (!SimpleStringUtils.hasText(cooperorgCode) || !SimpleStringUtils.hasText(packageNum) || CollectionsUtils.isEmpty(list)) {
				return new CreditDetailDto();
			}
			for (CreditDetailDto credit : list) {
				if (cooperorgCode.equals(credit.getCooperorgCode()) && packageNum.equals(credit.getPackageNum())) {
					return credit;
				}
			}
			return new CreditDetailDto();
		}
	}
}